const sqlQuery = require("./module/jcMysql");

let socketio = {};

function getSocket(server) {
    socketio.io = require("socket.io")(server);

    let io = socketio.io;
    io.on("connection", (socket) => {
        // 此处的socket是当前浏览器与服务器的连接对象
        console.log("建立了连接",socket.id);

        // 接收登录事件
        socket.on("login",async data=>{
            // 先要判断当前用户是否有人登录，如果有人登录的话，那么就断开连接
            let sqlStr1 = "select * from user where isonline = ? and username = ?";
            let result1 = await sqlQuery(sqlStr1,["true",data.username])
            if(result1.length>0){
                socket.to(result1[0].socketid).emit("logout",{
                    content:"你的账户已经在异地登录，请查看你的账户"
                })
            }
            // 修改数据库登录信息(socketid,isonline)
            let sqlStr = "update user set socketid=?,isonline=? where username=?";
            let result = await sqlQuery(sqlStr,[socket.id,"true",data.username])
            // 发送给前端登录成功
            socket.emit("login",{
                state:"ok",
                message:"登录成功"
            })

            // 重新获取用户数据
            let sqlStr2 = "select * from user"
            console.log(sqlStr2);
            
            // 等待获取mysql查询结果
            let result2 = await sqlQuery(sqlStr2)
            io.sockets.emit("users",Array.from(result2));

            // 最新未接收的信息
            let sqlStr3 = "select * from chat where isRead = ? and toUser =?";
            let result3 = await sqlQuery(sqlStr3,["false",data.username])
            socket.emit("unreadMsg",Array.from(result3));
            

        });

        // 断开连接
        socket.on("disconnect",async ()=>{
            // 修改数据库登录信息
            let sqlStr = "update user set socketid=?,isonline=? where socketid=?";
            let result = await sqlQuery(sqlStr,[null,null,socket.id])
        });

        // 等待查询结果
        socket.on("users",async ()=>{
            let sqlStr = "select * from user";
            // 等待获取mysql查询结果
            let result = await sqlQuery(sqlStr);
            socket.emit("users",Array.from(result))
        });

        // 获取前端发送的消息数据
        socket.on("sendMsg",async msg=>{
            //console.log(msg)
            //判断收消息的人是否在线

            let strSql = 'select * from user where username = ? and isonline= ?';
            let result = await sqlQuery(strSql, [msg.toUser.username, 'true']);
            if (result.length > 0) {
                //如果此人在线，那么直接发送消息；
                let toid = result[0].socketid;
                //console.log(toid)
                socket.to(toid).emit("accept", msg)
                //console.log(socket)
                //将聊天内容存放到数据库
                let strSql1 = 'insert into chat (`fromUser`,`toUser`,content,`sendTime`,isRead) values (?,?,?,?,?)';
                let arr1 = [msg.fromUser.username, msg.toUser.username, msg.content, msg.sendTime, 'true'];
                sqlQuery(strSql1, arr1)
            } else {
                //将聊天内容存放到数据库
                let strSql1 = 'insert into chat (`fromUser`,`toUser`,content,`sendTime`,isRead) values (?,?,?,?,?)';
                let arr1 = [msg.fromUser.username, msg.toUser.username, msg.content, msg.sendTime, 'false'];
                sqlQuery(strSql1, arr1)
            }
            
        });

        // 如果收到消息，就对消息状态进行更改为已读
        socket.on("readMsg",data=>{
            console.log("已读",data);
            
            let sqlStr = "update chat set isread=? where fromUser=? and toUser=?";
            sqlQuery(sqlStr,["true",data.target,data.self])
        })
        
    });
}

socketio.getSocket = getSocket

module.exports = socketio;
